package com.itheima.mobilesafe69.service;

import javax.crypto.spec.IvParameterSpec;

import com.itheima.mobilesafe69.R;
import com.itheima.mobilesafe69.db.dao.AddressDao;
import com.itheima.mobilesafe69.utils.ConstantValue;
import com.itheima.mobilesafe69.utils.PrefUtils;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

public class AddressService extends Service {
	private TelephonyManager mTM;
	private MyPhoneStateListener mPhoneStateListener;
	private final WindowManager.LayoutParams mParams = new WindowManager.LayoutParams();
	private WindowManager mWM;
	private View mViewToast;
	private String mQueryAddress;
	private Handler  mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			//收到消息以后,需要去让吐司上的文字做修改
			tv_toast_address.setText(mQueryAddress);
		};
	};
	private TextView tv_toast_address;
	private int mScreenWidth;
	private int mScreenHeight;
	private OutCallReceiver mOutCallReceiver;
	
	@Override
	public void onCreate() {
		// 1,开启服务后,要通过电话管理者对象,监听电话状态
		mTM = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		// 2,对电话状态监听(电话监听的对象,监听的事件类型监听电话状态),监听电话的权限
		mPhoneStateListener = new MyPhoneStateListener();
		mTM.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
		//3,获取窗体管理者对象,做吐司的添加
		mWM = (WindowManager) getSystemService(WINDOW_SERVICE);
		
		//获取屏幕宽度
		mScreenWidth = mWM.getDefaultDisplay().getWidth();
		mScreenHeight = mWM.getDefaultDisplay().getHeight();
				
		//注册一个监听播出电话广播接受者,监听此广播时,需要添加权限
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(Intent.ACTION_NEW_OUTGOING_CALL);
		
		mOutCallReceiver = new OutCallReceiver();
		registerReceiver(mOutCallReceiver, intentFilter);
		
		super.onCreate();
	}
	
	class OutCallReceiver extends BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent) {
			//获取播出电话号码,然后将其查询结果并且显示在悬浮在窗体的吐司上
			//系统提供的获取播出电话号码的api
			String phone = getResultData();
			showToast(phone);
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onDestroy() {
		// 取消对电话状态的监听
		if (mTM != null && mPhoneStateListener != null) {
			mTM.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
		}
		//服务销毁时,广播接受者也没有意义,所以给其注销掉
		if(mOutCallReceiver!=null){
			unregisterReceiver(mOutCallReceiver);
		}
		super.onDestroy();
	}

	class MyPhoneStateListener extends PhoneStateListener {
		// 回调方法
		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			switch (state) {
			case TelephonyManager.CALL_STATE_IDLE:
				// 空闲(移除吐司)
				if(mWM!=null && mViewToast!=null){
					//在电话挂机的时候可以将吐司移除掉
					mWM.removeView(mViewToast);
				}
				break;
			case TelephonyManager.CALL_STATE_RINGING:
				// 正在响铃(弹出吐司)
				showToast(incomingNumber);
				break;
			case TelephonyManager.CALL_STATE_OFFHOOK:
				// 通话中
				break;
			}
			super.onCallStateChanged(state, incomingNumber);
		}
	}

	public void showToast(final String incomingNumber) {
		// 自定义吐司样式,时间
		//给吐司定义出来的参数(宽高,类型,触摸方式)
		final WindowManager.LayoutParams params = mParams;
		params.height = WindowManager.LayoutParams.WRAP_CONTENT;
		params.width = WindowManager.LayoutParams.WRAP_CONTENT;
		params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
//				| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE	因为吐司需要根据手势去移动,所以必须要能触摸
				| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
		params.format = PixelFormat.TRANSLUCENT;
		params.type = WindowManager.LayoutParams.TYPE_PHONE;//不在和吐司类型相互绑定,通话的类型相互绑定
		//将吐司放置在左上角显示
		params.gravity=Gravity.TOP+Gravity.LEFT;
		params.setTitle("Toast");
		
		//将sp记录的位置获取出来,作为来电归属的显示位置
		int locationX = PrefUtils.getInt(getApplicationContext(), ConstantValue.LOCATION_X, 0);
		int locationY = PrefUtils.getInt(getApplicationContext(), ConstantValue.LOCATION_Y, 0);
		
		//将记录的xy坐标,左上角的坐标赋给吐司控件
		params.x = locationX;
		params.y = locationY;
		
		new Thread(){
			public void run() {
				mQueryAddress = AddressDao.queryAddress(incomingNumber);
				//通过消息机制告知主线程可以去,显示归属地位置
				mHandler.sendEmptyMessage(0);
			};
		}.start();
		//定义图片id所在数组
		int[] drawableIds = new int[]{
				R.drawable.call_locate_white,
				R.drawable.call_locate_orange,
				R.drawable.call_locate_blue,
				R.drawable.call_locate_gray,
				R.drawable.call_locate_green
		};
		
		//定义吐司样式,xml--->view
		mViewToast = View.inflate(this,R.layout.toast_view, null);
		tv_toast_address = (TextView) mViewToast.findViewById(R.id.tv_toast_address);
		
		//从sp中获取选中的吐司样式的索引,获取数组中指定索引的图片id,用作展示
		int toast_style_index = PrefUtils.getInt(this,ConstantValue.TOAST_STYLE_INDEX, 0);
		tv_toast_address.setBackgroundResource(drawableIds[toast_style_index]);
		
		mViewToast.setOnTouchListener(new OnTouchListener() {
			private int startX;
			private int startY;

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					startX = (int) event.getRawX();
					startY = (int) event.getRawY();
					
					break;
				case MotionEvent.ACTION_MOVE:
					int moveX = (int) event.getRawX();
					int moveY = (int) event.getRawY();
					
					int disX = moveX - startX;
					int disY = moveY - startY;
					
					params.x = params.x+disX;
					params.y = params.y+disY;
					
					//在窗体中仅仅告知吐司的左上角的坐标
					if(params.x<0){
						params.x = 0;
					}
					if(params.y<0){
						params.y = 0;
					}
					
					if(params.x>mScreenWidth-mViewToast.getWidth()){
						params.x = mScreenWidth-mViewToast.getWidth();
					}
					
					if(params.y>mScreenHeight-22-mViewToast.getHeight()){
						params.y = mScreenHeight-22-mViewToast.getHeight();
					}
					
					//告知吐司在窗体上刷新
					mWM.updateViewLayout(mViewToast, params);
					
					//在第一次移动完成后,将最终坐标作为第二次移动的起始坐标
					startX = (int) event.getRawX();
					startY = (int) event.getRawY();
					break;
				case MotionEvent.ACTION_UP:
					//记录最后放手的位置
					PrefUtils.putInt(getApplicationContext(), ConstantValue.LOCATION_X, params.x);
					PrefUtils.putInt(getApplicationContext(), ConstantValue.LOCATION_Y, params.y);
					break;
				}
				//此处返回true,仅仅为了去响应拖拽事件
				return true;
			}
		});
		
		//将吐司放置在窗体上WindowManager,权限
		mWM.addView(mViewToast, params);
	}
}
